package db

import _ "github.com/go-sql-driver/mysql"
import "github.com/jmoiron/sqlx"

func InitDb() *sqlx.DB {
	dsn := "root:123456@tcp(127.0.0.1:3306)/family-paperless"
	db, err := sqlx.Connect("mysql", dsn)
	if err != nil {
		panic(err)
	}
	return db
}

func MapScanWithSortedKeys(r *sqlx.Rows, dest map[string]interface{}) ([]string, error) {
	columns, err := r.Columns()
	if err != nil {
		return nil, err
	}

	values := make([]interface{}, len(columns))
	for i := range values {
		values[i] = new(interface{})
	}

	err = r.Scan(values...)
	if err != nil {
		return nil, err
	}

	// to keep ordering consistent
	var keys []string
	for i, column := range columns {
		dest[column] = *(values[i].(*interface{}))
		keys = append(keys, column)
	}

	return keys, r.Err()
}
